package com.hk.service.sys.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hk.commons.*;
import com.hk.commons.enm.LogTypeEnum;
import com.hk.commons.enm.MqEventType;
import com.hk.commons.entity.AccountBalance;
import com.hk.commons.entity.sys.*;
import com.hk.commons.utils.EncryptDecryptUtils;
import com.hk.commons.utils.HttpUtil;
import com.hk.commons.utils.MsgTypeConstants;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.MqCenterMsg;
import com.hk.service.IOrganization_New;
import com.hk.service.IUserChannel;
import com.hk.service.kyc.ICoupon;
import com.hk.service.mq.IMq;
import com.hk.service.sys.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hk.commons.entity.LogUtil;
import com.hk.commons.entity.Organization;
import com.hk.commons.vo.app.SysUserMsg;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IOrganization;
import com.hk.service.impl.OrganizationImpl;
import com.hk.service.kyc.ILogUtil;

@Service
public class SysUserImpl extends BaseServiceImpl<SysUser> implements ISysUser {

	private Logger logger = LoggerFactory.getLogger(SysUserImpl.class);

	@Value("${qingniu.pdf}")
	private String QN_PDF;

	@Value("${payServer.baseUrl}")
	private String payServerUrl;

	@Value("${payServer.apiKey}")
	private String payServerApiKey;

	@Resource
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private IOrganization orgService;

	@Autowired
	private ISysRole sysRoleService;

	@Autowired
	private IUserChannel channelService;

	@Autowired
	private ISysUserRoles sysUserRolesService;

	@Autowired
	private ILogUtil logService;


	@Autowired
	private IOrganization_New orgNewService;


	@Autowired
	private IMq mqService;

	@Autowired
	private ICoupon couponService;

	@Autowired
	private IAnswer answerService;

	@Autowired
	private IApiSecret apiSecretService;


	@Override
	public SysUser findById(Long id) {

		//logger.info("SysUser findById user id == {}", id);
		if (id == null) {
			return null;
		}

		// 如果id 大于14位则只取14位
		//id = checkId(id);


		SysUser user = this.getById(id);

		return user;
	}

	@Override
	public String getNameById(Long id) {
		String str = null;
		SysUser user = findById(id);
		if (user != null) {
			str = user.getRealName();
		}
		return str;
	}

	@Override
	public Long add(SysUser o) {
		Long id = LongId.get();
		o.setId(id);
		o.setRegistCts(System.currentTimeMillis());
		super.save(o);
		return id;
	}

	@Override
	public SysUser getByAccount(String account) {
		return getByPhoneNum(account,ConstantUser.NOT_CLOSE_ACCOUNT);
	}

	@Override
	public SysUser getByAccountId(String accountId) {
		if (StringHelper.isEmpty(accountId)) {
			return null;
		} else {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("accountId", accountId);
			return getByFilter(hqlFilter);
		}

	}

	@Override
	public SysUser getByMobileId(String mobileId) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("mobileId", mobileId);
		return getByFilter(hqlFilter);
	}

	@Override
	public SysUserDummy getDummyByAccount(String account) {
		SysUser user = null;
		SysUserDummy dummyUser = null;
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("name", account);
		user = getByFilter(hqlFilter);
		if (user != null) {
			ReqToModelHelper.copyReqValueToModel(user, dummyUser);
		}

		return dummyUser;
	}

	/**
	 *根据手机号获取用户
	 * @param phoneNum
	 * @return
	 */
	@Override
	public SysUser getByPhoneNum(String phoneNum) {
		return getByPhoneNum(phoneNum,ConstantUser.NOT_CLOSE_ACCOUNT);
	}

	/**
	 * 根据手机号和销户状态获取用户
	 * @param phoneNum
	 * @param closeAccount 销户状态（0：末销户，1：已销户）
	 * @return
	 */
	@Override
	public SysUser getByPhoneNum(String phoneNum, Integer closeAccount){
		SysUser user = null;
		if(StringHelper.isBlank(phoneNum)){
			return user;
		}

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("name", phoneNum);
		if( closeAccount != null){
			hqlFilter.addEQFilter("closeAccount",closeAccount);
		}
		user = getByFilter(hqlFilter);
		return user;
	}

	// 根据用户id ,获取理财师id
	@Override
	public Long getFinUserIdByUserId(Long userId) {
		Long finUserId = null;
		SysUser user = findById(userId);
		if (user != null && StringHelper.isNotEmpty(user.getRecommendCode())) {
			SysUser finUser = getByPhoneNum(user.getRecommendCode());
			if (finUser != null) {
				finUserId = finUser.getId();
			}
		}
		return finUserId;
	}

	@Override
	public SysUser findFinUserByUserId(Long userId) {
		// 根据用户id ,获取理财师id
		SysUser user = findById(userId);
		SysUser finUser = null;
		if (user != null && StringHelper.isNotEmpty(user.getRecommendCode())) {
			finUser = getByPhoneNum(user.getRecommendCode());
		}
		return finUser;
	}

	@Override
	public SysUserDummy findDummyById(Long id) {
		SysUser user = null;
		SysUserDummy dummyUser = new SysUserDummy();
		user = getById(id);
		if (user != null) {
			ReqToModelHelper.copyReqValueToModel(user, dummyUser);
		}
		return dummyUser;
	}

	@Override
	public SysUser delete(Long id) {
		SysUser sysUser = new SysUser();

		// 如果id 大于14位则只取14位
		//id = checkId(id);

		sysUser.setId(id);
		super.delete(sysUser);
		return sysUser;
	}

	@Override
	public boolean existById(Long id) {
		// TODO Auto-generated method stub
		SysUser sysUser = findById(id);
		return sysUser != null ? true : false;
	}

	@Override
	public boolean existByName(String name) {
		// TODO Auto-generated method stub
		SysUser sysUser = getByAccount(name);
		return sysUser != null ? true : false;
	}

	@Override
	public boolean existByMobileId(String mobileId) {
		// TODO Auto-generated method stub

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("mobileId", mobileId);
		SysUser sysUser = getByFilter(hqlFilter);
		return sysUser != null ? true : false;
	}

	/**
	 * 根据orgId, 获取该部门下所有的用户
	 * 
	 * @param orgID
	 * @return
	 */
	@Override
	public List<SysUser> getUserByOrgId(Integer orgID) {
		OrganizationImpl orgService = new OrganizationImpl();
		Organization organization = orgService.findById(orgID);

		HqlFilter hqlFilter = new HqlFilter();

		String sqlStr = " and recommendCode in  ( select  name  FROM  SysUser where orgId in (SELECT id FROM  t_organization where code like ('ORGID-%')))";

		//sqlStr = sqlStr.replace("ORGCODE", organization.getCode()).trim();

		hqlFilter.addSql(sqlStr);

		List<SysUser> userList = this.findByFilter(hqlFilter);
		return userList;

	}

	@Override
	public List<SysUser> getAll() {
		HqlFilter hqlFilter = new HqlFilter();
		return findByFilter(hqlFilter);
	}

	/**
	 * 
	 * 根据用户的支付方式反向更新用户的身份信息
	 */
	@Override
	public void upUserByPayment(SysUser req) {

		Long userId = req.getId();
		String identity = req.getIdentity();
		String realName = req.getRealName();

		SysUser user = findById(userId);
		if (user != null
				&& (StringHelper.isEmpty(user.getIdentity()) || StringHelper
						.isEmpty(user.getRealName()))) {

			user.setIdentity(identity);
			user.setRealName(realName);

			// 设置性别 男:M 0, 女 : F, 1
			Integer gender = (IdcardUtils.getGenderByIdCard(identity) == "M" ? 0
					: 1);
			user.setGender(gender);

			// 设置出生日期
			String birthdayStr = IdcardUtils.getBirthByIdCard(identity);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyymmdd");

			try {
				Long birthdayLong = formatter.parse(birthdayStr).getTime();
				user.setBirthday(birthdayLong);
			} catch (ParseException e) {

				e.printStackTrace();
			}
			
			
			// 更改客户省份
			if (StringHelper.isEmpty(user.getLocation())) {
				String location = IdcardUtils.getCityByIdCard(identity);
				user.setLocation(location);
			}
			
			update(user);
		}
	}

	@Override
	public Long checkId(Long id) {
		/*
		Long newId = id;

		if (id != null && id.toString().length() > 14) {
			String idStr = id.toString();
			String newIdStr = idStr.substring(0, 14);
			newId = Long.valueOf(newIdStr);
		}
		return newId;
		*/
		return id;
	}

	/**
	 * 设置用户的绑卡信息为已支付
	 */
	@Override
	public void upUserByPayment(Long userId, String accountId, String identity,
			String accountName) {
		logger.info("upUserByPayment userId = " + userId + "  accountId = "
				+ accountId + "  identity = " + identity + "  accountName = "
				+ accountName);
		SysUser user = this.findById(userId);
		if (user != null) {
			if (StringHelper.isNotEmpty(accountId)
					&& StringHelper.isEmpty(user.getAccountId())) {
				user.setAccountId(accountId);
			}

			if (StringHelper.isNotEmpty(identity)) {

				user.setIdentity(identity);
				// 更改客户生日和省份

				String birthday = IdcardUtils.getBirthByIdCard(identity);
				if (user.getBirthday() == null) {
					Long birthDayLong = DateUtil.transferStringToLong(birthday);
					user.setBirthday(birthDayLong);
				}

				// 更改客户省份
				if (StringHelper.isEmpty(user.getLocation())) {
					String location = IdcardUtils.getCityByIdCard(identity);
					user.setLocation(location);
				}

			}

			if (StringHelper.isNotEmpty(accountName)) {
				user.setRealName(accountName);
			}

			if (StringHelper.isEmpty(user.getPaymentNo())) {
				user.setPaymentNo("*********"); // 暂时兼容， 为了统计日报
			}

			user.setTieCard(Constant.USER_TIE_CARD_TRUE);

			logger.info("upUserByPayment will upd user ");
			update(user);
		}

	}

	@Override
	public SysUser getUserByRealName(String realName) {
		SysUser user = null;

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("RealName", realName);
		List<SysUser> userList = this.findByFilter(hqlFilter);
		if (userList.size() > 0) {
			user = userList.get(0);
		}

		return user;
	}

	@Override
	public List<SysUser> getUserListByRealName(String realName) {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addLKFilter("RealName", realName);
		List<SysUser> userList = this.findByFilter(hqlFilter);

		return userList;
	}

	@Override
	public List<SysUser> getUserByRecommendCode(String recommendCode) {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("recommendCode", recommendCode);
		hqlFilter.addEQFilter("isInside", 0);
		List<SysUser> userList = this.findByFilter(hqlFilter);

		return userList;
	}

	@Override
	public Boolean isTester(Long userId) {
		Boolean result = false;
		if (userId != null && existById(userId)) {
			SysUser user = findById(userId);
			if (user.getOrgId() != null) {
				Organization org = orgService.findById(user.getOrgId());
				if (org != null && org.getCode().contains("-442-")) {
					result = true;
				}
			}
		}
		return result;
	}

	@Override
	public Integer getRelUserNumById(Long userId) {
		Integer size = 0;
		SysUser finUser = findById(userId);


		if (finUser != null) {
			String recommendCode = finUser.getName();

			String sql = "SELECT count(*) FROM  SysUser  where isInside = 0 and  recommendCode = "
					+ recommendCode;

			size = jdbcTemplate.queryForObject(sql, Integer.class);
		}

		return size;
	}

	@Override
	public Integer getRelTieCardUserNumById(Long userId) {
		Integer size = 0;
		SysUser finUser = findById(userId);


		if (finUser != null) {
			String recommendCode = finUser.getName();

			String sql = "SELECT count(*) FROM  SysUser  where isInside = 0 and tieCard = 1 and recommendCode = "
					+ recommendCode;

			size = jdbcTemplate.queryForObject(sql, Integer.class);
		}

		return size;
	}

	/**
	 * 根据用户Id,查询账户余额
	 * @param userId
	 * @return
	 */
	@Override
	public AccountBalance getBalance(Long userId) {
		if(userId == null || StringUtils.isBlank(payServerUrl) || StringUtils.isBlank(payServerApiKey)){
			return null;
		}

		ApiSecret secret = apiSecretService.findByApikey(payServerApiKey);
		if(secret == null){
			return null;
		}

		String url = payServerUrl+"payServer/app/checkBalance";
		Map<String,String> params = new HashMap<>();
		params.put("userId",userId.toString());
		params.put("apiKey",payServerApiKey);
		String sign = EncryptDecryptUtils.getYMSign(secret.getApiSecret(),params);
		params.put("sign",sign);

		Map<String,String> headers = new HashMap<>();
		headers.put("Content-Type","application/json");
		String response = HttpUtil.postHttpBody(url,JSON.toJSONString(params),headers);
		if (response == null){
			return null;
		}

		try {
			JSONObject object = JSON.parseObject(response);
			if(object.getIntValue("resultCode") == 200){
				AccountBalance result = object.getObject("result",AccountBalance.class);
				return result;
			}
		}catch (Exception e){
			logger.error("查询账户余额转换异常",e);
		}
		return null;
	}


	@Override
	public Boolean isFinUserById(Long userId) {
		Boolean result = false;
		SysUser user = findById(userId);
		if (user != null && user.getOrgId() != null
				&& !(user.getOrgId().equals(ConstantUser.USER_ORG_WUZHU))) {
			result = true;
		}

		return result;
	}

	@Override
	public Boolean isFinUserByPhoneNum(String phoneNum) {

		if (StringHelper.isEmpty(phoneNum)) {
			return false;
		}

		Boolean result = false;

		SysUser user = getByPhoneNum(phoneNum);
		if (user != null && user.getOrgId() != null
				&& !(user.getOrgId().equals(ConstantUser.USER_ORG_WUZHU))) {
			result = true;
		}

		return result;
	}

	@Override
	public Boolean cleanRecommandCordByCode(String recommandCode, Long actUserId) {
		logger.info("清空该名下所有直接客户的推荐码为空  actUserId = {}, recommandCode={}",
				actUserId, recommandCode);
		if (StringHelper.isEmpty(recommandCode)) {
			return false;
		}
		List<SysUser> userList = getUserByRecommendCode(recommandCode);
		if (userList != null && userList.size() > 0) {
			for (SysUser user : userList) {
				LogUtil logRecord = new LogUtil();

				logRecord.setActUserId(actUserId);
				logRecord.setType(ConstantLog.LOG_TYPE_USER_IMP);
				logRecord.setChgDesc("理财师离职或更改渠道，清空直属客户推荐码 用户名为"
						+ user.getRealName());

				logRecord.setRecordId(user.getId());
				logRecord.setUserId(user.getId());

				// 在日志表中保存修改之前的镜像
				String beforeImgStr = JsonUtils
						.toJson(getRespUser(user.getId()));
				logRecord.setBeforeImg(beforeImgStr);

				user.setRecommendCode(null);
				logger.info(
						"清空该名下所有直接客户的推荐码为空  actUserId = {}, userId={}, userName={}",
						actUserId, user.getId(), user.getRealName());
				update(user);

				// 在日志中保存修改之后的镜像
				String afterImgStr = JsonUtils
						.toJson(getRespUser(user.getId()));
				logRecord.setAfterImg(afterImgStr);

				// 加入日志表中
				logService.add(logRecord);

			}
		}

		return true;
	}

	/**
	 * 通过userId, 将用户信息进行封装，然后传给后台
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public SysUserMsg getRespUser(Long userId) {
		SysUser sysUser = findById(userId);
		SysUserMsg sresp = new SysUserMsg();

		if (sysUser == null) {
			return sresp;
		}
		ReqToModelHelper.copyReqValueToModel(sysUser, sresp);
		List<SysUserRoles> sysUserRolesList = sysUserRolesService
				.getByUserAccount(sysUser.getName());
		if (sysUserRolesList != null && !sysUserRolesList.isEmpty()) {
			String sysRoleNames = "";
			for (SysUserRoles sysUserRoles : sysUserRolesList) {
				SysRole sysRole = sysRoleService.findById(sysUserRoles
						.getRoleId());
				if (sysRole != null) {
					sysRoleNames += "," + sysRole.getName();
				}
			}
			sresp.setSysUserRoleList(sysUserRolesList);
			sresp.setSysRoleNames(StringUtils.isEmpty(sysRoleNames) ? ""
					: sysRoleNames.substring(1));
		}

		if (sysUser.getOrgId() != null) {
			Organization org = orgService.findById(sysUser.getOrgId());
			if (org != null) {
				sresp.setOrgName(org.getName());
				sresp.setOrgDepName(orgService.getDepNameById(org.getId()));
			}
		}

		String sql = "select scoreDesc, cts, kycPdfUrl from t_answer_info where userId = ? order by cts desc";
		List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql, new Object[] { sysUser.getId() });

		DateTimeFormatter yearMonthDay = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		if (results.size() > 0) {
			Map<String, Object> result = results.get(0);

			LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli((Long)result.get("cts")), ZoneId.systemDefault());
			String timeString = localDateTime.format(yearMonthDay);
			sresp.setScoreCts(timeString);

			LocalDateTime now = LocalDateTime.now();
			LocalDateTime nextYear = localDateTime.plusYears(1L);

			if (now.compareTo(nextYear) <= 0) {
				sresp.setScoreDesc(String.valueOf(result.get("scoreDesc")));
			} else {
				sresp.setScoreDesc(String.valueOf(result.get("scoreDesc")) + "<br/>（已过期）");
			}

			sresp.setKycPdfUrl(QN_PDF + result.get("kycPdfUrl"));
		} else {
			sresp.setScoreDesc("未测评");
			sresp.setScoreCts("");
		}

		sresp.setOrgId(sysUser.getOrgId());
		sresp.setChannelId(sysUser.getChannel());
		sresp.setIsInside(sysUser.getIsInside());
		sresp.setChannel(sysUser.getChannel());
		sresp.setBirthday(sysUser.getBirthday());
		sresp.setEntryTime(sysUser.getEntryTime());
		sresp.setLeaveTime(sysUser.getLeaveTime());
		sresp.setLocation(sysUser.getLocation());


		if(StringHelper.isNotEmpty(sysUser.getIfaHtmlUrl())){
			sresp.setIfaUrl(QN_PDF + sysUser.getIfaPdfUrl());
		}


		sresp.setChannelName(channelService.getChannelNameByChannelId(sysUser.getChannel()));

		sresp.setPwd(null); //重置密码

		// 如果离职时间不为空，则设置用户已离职
		if (sysUser.getLeaveTime() != null) {
			sresp.setIsLeave(ConstantUser.USER_LEAVE);
		}

		sresp.setRelUserNum(getRelUserNumById(sysUser.getId()));

		sresp.setRelTieCardUserNum(getRelTieCardUserNumById(userId));

		// 添加客户理财师的属性
		if (StringHelper.isNotEmpty(sysUser.getRecommendCode())) {
			// 添加理财师全名
			sresp.setRecommendCode(sysUser.getRecommendCode());

			SysUser finUser = getByAccount(sysUser.getRecommendCode());
			if (finUser != null && finUser.getIsInside() == 1) {


				if (StringHelper.isNotEmpty(finUser.getRealName())) {
					sresp.setFinUserName(finUser.getRealName());
				}

				// 添加理财师所属渠道
				if (finUser.getOrgId() != null) {
					Organization org = orgService.findById(finUser.getOrgId());
					if (org != null) {
						String depFullName = org.getFlag02();
						if (StringHelper.isNotEmpty(depFullName)) {
							sresp.setFinDepFullName(depFullName);
						}
					}
				}

			}
		}

		return sresp;
	}

	@Override
	public Boolean checkFinancialFlanners(SysUser user) {
		Boolean result = false;
		if(user.getIsInside() == 1){
			result = true;
		}
		return result;
	}

	@Override
	public void update(SysUser user, Long actUserId) {
		
		/**日志开始**/
		LogUtil logRecord = new LogUtil();

		logRecord.setActUserId(actUserId);
		logRecord.setType(ConstantLog.LOG_TYPE_USER_IMP);

		String realName = "";
		if (StringHelper.isNotEmpty(user.getRealName())) {
			realName = user.getRealName();
		}
		logRecord.setChgDesc("修改用户推荐码或渠道 用户名为   : " + realName);

		logRecord.setRecordId(user.getId());
		logRecord.setUserId(user.getId());

		// 在日志表中保存修改之前的镜像
		String beforeImgStr = JsonUtils.toJson( getRespUser(user.getId()));
		logRecord.setBeforeImg(beforeImgStr);
		
		update(user);

		/**日志开始**/
		String afterImgStr = JsonUtils.toJson(getRespUser(user.getId()));
		logRecord.setAfterImg(afterImgStr);
		
		// 加入日志表中
		logService.add(logRecord);
	}

	@Override
	public void update(SysUser user, Long actUserId, Integer logType) {

		/**日志开始**/
		LogUtil logRecord = new LogUtil();

		logRecord.setActUserId(actUserId);
		logRecord.setType(ConstantLog.LOG_TYPE_USER_IMP);

		String realName = "";
		if (StringHelper.isNotEmpty(user.getRealName())) {
			realName = user.getRealName();
		}
		logRecord.setChgDesc(LogTypeEnum.getTypeMsg(logType) + " 用户名：" + user.getRealName());

		logRecord.setRecordId(user.getId());
		logRecord.setUserId(user.getId());

		// 在日志表中保存修改之前的镜像
		String beforeImgStr = JsonUtils.toJson( getRespUser(user.getId()));
		logRecord.setBeforeImg(beforeImgStr);

		update(user);

		/**日志开始**/
		String afterImgStr = JsonUtils.toJson(getRespUser(user.getId()));
		logRecord.setAfterImg(afterImgStr);

		// 加入日志表中
		logService.add(logRecord);
	}


	@Override
	public Boolean reSetOrgByCode(String recommandCode, Long actUserId) {
		logger.info("理财师变为非理财师，修改客户的组织架构为最近的无主客户服务部门  actUserId = {}, recommandCode={}",
				actUserId, recommandCode);
		if (StringHelper.isEmpty(recommandCode)) {
			return false;
		}

		List<SysUser> userList = getUserByRecommendCode(recommandCode);
		if (userList != null && userList.size() > 0) {
			for (SysUser user : userList) {
				Integer latestUZ = orgNewService.getLatestWuZhu(user.getOrgId());
				user.setOrgId(latestUZ);
				update(user, actUserId, LogTypeEnum.TYPES_2.getTypeId());
			}
		}
		return true;
	}


	@Override
	public CheckInfo updateRecommandCode(String recommandCode, Long userId, Long actUserId) {

		CheckInfo checkInfo = new CheckInfo();
		try {
			logger.info("updateSysUserCode 操作者的id = {}, 操作对象的id = {}, 新的推荐码  = {}", actUserId, userId, recommandCode);
			SysUser user = findById(userId);
			//如果推荐码设置为空
			if(StringHelper.isEmpty(recommandCode)){
				if(user.getIsInside() != null && user.getIsInside() == 0){
					user.setRecommendCode(null);

					Integer orgId = user.getOrgId();

					Integer latestUZ = orgNewService.getLatestWuZhu(orgId);

					logger.info("用户原来组织架构为={}, 新的组织架构为={} ", orgId, latestUZ);
					if(latestUZ != null){
						user.setOrgId(latestUZ);
						logger.info("清空用户推荐码，设置用户为无主， 用户原来组织架构为={}, 新的组织架构为={} ", orgId, latestUZ);
					}
				}else{
					checkInfo.setResult(false);
					checkInfo.setResultMsg("该用户为理财师，推荐码必须是自己的手机号。用户手机号是：" + user.getName());
					return checkInfo;
				}
			}else{
				if(user.getIsInside() != null && user.getIsInside() == 1){
					checkInfo.setResult(false);
					checkInfo.setResultMsg("该用户为理财师，推荐码必须是自己的手机号。用户手机号是：" + user.getName());
					return checkInfo;
				}

				SysUser finUser = getByPhoneNum(recommandCode);

				if(finUser == null){
					checkInfo.setResult(false);
					checkInfo.setResultMsg("该推荐码对应的理财师不存在，此次修改失败！");
					return checkInfo;
				}
				if(finUser.getIsInside() == null || finUser.getIsInside() != 1) {
					checkInfo.setResult(false);
					checkInfo.setResultMsg("该推荐码对应的用户不是理财师，此次修改失败！");
					return checkInfo;
				}

				user.setRecommendCode(recommandCode);
				user.setRecommendId(finUser.getId());
				user.setOrgId(finUser.getOrgId());
				user.setChannel(finUser.getChannel());
			}

			this.update(user, actUserId);


			ExecutorService executor = Executors.newFixedThreadPool(1);

			Runnable task = () -> {
				this.checkAndSendRegistCard(userId);
			};
			executor.execute(task);
			executor.shutdown();






			checkInfo.setResult(true);
			checkInfo.setResultMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			checkInfo.setResult(false);
			checkInfo.setResultMsg("操作异常，请重试");
		}
		return checkInfo;
	}

	@Override
	public CheckInfo updateOrgId(Organization org, Long userId, Long actUserId, Integer chgCustomer) {
		SysUser user = findById(userId);
		//首先更改本人的组织架构信息
		CheckInfo checkInfo = this.updateUserOrgId(org, user, actUserId);

		if(user.getIsInside() != null && user.getIsInside() == 1 && chgCustomer == 1){

			logger.info("将会修改关联客户的组织架构");
			List<SysUser> userList = this.getUserByRecommendCode(user.getName());
			logger.info("将会修改关联客户的组织架构 userList size = {}", userList.size());

			userList.parallelStream()
					.map(sysUser -> this.updateUserOrgId(org, sysUser, actUserId))
					.collect(Collectors.toList());
		}

		return checkInfo;
	}

	@Override
	public CheckInfo updateUserOrgId(Organization org, SysUser user, Long actUserId) {
		CheckInfo checkInfo = new CheckInfo();
		try {
			logger.info("updateOrgId 操作者的id = {}, 操作对象的id = {}, 新的组织架构id   = {}", actUserId, user.getId(), org.getId());
			if(user == null) {
				checkInfo.setResult(false);
				checkInfo.setResultMsg("被操作的用户不存在。用户手机号是：" + user.getName());
				return checkInfo;
			}

			user.setOrgId(org.getId());
			user.setChannel(org.getChannel());

			this.update(user, actUserId);

			checkInfo.setResult(true);
			checkInfo.setResultMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			checkInfo.setResult(false);
			checkInfo.setResultMsg("操作异常，请重试");
		}
		return checkInfo;
	}

	@Override
	public CheckInfo checkAndSendRegistCard(Long userId) {

		CheckInfo checkInfo = new CheckInfo();
		checkInfo.setResult(false);

		String dispatchEvent = MqEventType.USER_REGISTRATION.toString();
		if( checkNeedSendRegistCard(userId)){

			MqCenterMsg msg = MqCenterMsg.getMqCenterMsg(userId, dispatchEvent);
			mqService.setMessage(MqCenterMsg.CENTER_QUEUE_NAME, msg);
			checkInfo.setResult(true);
		}else{
			checkInfo.setResultMsg("用户已获得该类卡券，此次派送失败！");
		}

		return checkInfo;
	}


	public boolean checkNeedSendRegistCard(Long userId){

		String actType = "REGISTRATION";
		Integer cardCount  = couponService.countByActivityType(userId, actType);
		logger.info("actType ={}, cardCount ={}", actType, cardCount);
		return cardCount >= 1 ? false:true;
	}

}
